package core.dao;

import core.dto.UserListDto;
import core.entity.User;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Repository
public class UserDAO {

    @PersistenceContext
    EntityManager em;

    public User findUser(long id) {
        return em.find(User.class, id);

    }

    public User findUserByFirstName(String firstName) {
        return em.find(User.class, firstName);

    }

    public List<User> getAllUsers(){
        return em.createQuery("SELECT u from User u", User.class)
                .getResultList();
    }

    public void createUser(User user){
        em.persist(user);
    }

    public void removeUser(User user){
        em.remove(user);
    }

    public void updateUser(User user) {
        em.merge(user);
    }

    public List<User> selectUserWhoCreatedTopics(){
        return em.createQuery("SELECT u FROM User u JOIN u.topics", User.class)
                .getResultList();
    }

    public void changeNameById(User user){

        em.createQuery("UPDATE User t SET t.firstName  = 'edited' where t.id = " + user.getId(), User.class);
    }

    public void deleteUser(User user){
        em.createQuery("DELETE from User t WHERE t.id = " + user.getId(), User.class);
    }

    public List<UserListDto> getAllNames(){
        List<UserListDto> result = em.createQuery("SELECT new core.dto.UserListDto(t.id, t.firstName, t.lastName) FROM User t")
                .getResultList();

        return result;
    }

    public long getUserCount(){
        return (long) em.createQuery("SELECT COUNT(u) FROM User u")
                .getSingleResult();
    }
}
